﻿/**
 * 帮助类
 */
var logger = require('./logger').logger;

module.exports = {
    isArray: ('isArray' in Array) ? Array.isArray : function (value) {
        return toString.call(value) === '[object Array]';
    },
    isDate: function (value) {
        return toString.call(value) === '[object Date]';
    },
    isObject: function (value) {
        return toString.call(value) === '[object Object]';
    },
    isFunction: function (value) {
        return !!value && toString.call(value) === '[object Function]';
    },
    isNumber: function (value) {
        return typeof value === 'number' && isFinite(value);
    },
    isNumeric: function (value) {
        return !isNaN(parseFloat(value)) && isFinite(value);
    },
    isString: function (value) {
        return typeof value === 'string';
    },
    isBoolean: function (value) {
        return typeof value === 'boolean';
    },
    isEmpty: function (value, allowEmptyString) {
        return (value === undefined || value === null) || (!allowEmptyString ? value === '' : false) || (this.isArray(value) && value.length === 0);
    },
    
    /**
     * Normalize a port into a number, string, or false.
     */
    normalizePort: function (val) {
        var port = parseInt(val, 10);

        if (isNaN(port)) {
            // named pipe
            return val;
        }

        if (port >= 0) {
            // port number
            return port;
        }

        return false;
    },

    /**
     * 从request请求中取出store.load的参数
     * 
     * @param {Request} req 
     * @returns {Object} {page: 1, start: 0, limit: 25, filter: [], sort: []}
     */
    getStoreParams: function (req) {
        var startStr = req.query.hasOwnProperty('start') ? req.query.start : req.body.start, 
            pageStr = req.query.hasOwnProperty('page') ? req.query.page : req.body.page,
            limitStr = req.query.hasOwnProperty('limit') ? req.query.limit : req.body.limit,
            sortStr = req.query.hasOwnProperty('sort') ? req.query.sort : req.body.sort,
            filterStr = req.query.hasOwnProperty('filter') ? req.query.filter : req.body.filter,
            storeParams = {
                start: 0, //25
                page: 1, //2 
                limit: 25, //25
                sort: [],
                filter: []
            };
        if (!this.isEmpty(startStr)) storeParams.start = parseInt(startStr);
        if (!this.isEmpty(pageStr)) storeParams.page = parseInt(pageStr);
        if (!this.isEmpty(limitStr)) storeParams.limit = parseInt(limitStr);
        if (!this.isEmpty(sortStr)) storeParams.sort = JSON.parse(sortStr);
        if (!this.isEmpty(filterStr)) storeParams.filter = JSON.parse(filterStr);

        return storeParams;
    }
};